package com.me.services.memory;

import cn.hutool.crypto.digest.DigestUtil;
import com.me.model.normal.NormalUser;
import com.me.services.IUserService;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//吕旺平 宋杰
public class UserMemoryService implements IUserService<NormalUser> {
	private static Map<String, NormalUser> userMap = new HashMap();
	
	public UserMemoryService() {
		if (userMap.size() == 0) addUser(
				new NormalUser(
					UUID.randomUUID().toString(), "123@qq.com","test",
					"123", "", "某某人", 1,"123456"
				),
				true
		);
	}
	
	public boolean addUser(NormalUser user) {
		return addUser(user, false);
	}
	
	public boolean addUser(NormalUser user, boolean isAdmin) {
		user.setId(UUID.randomUUID().toString());
		user.setAdmin(isAdmin);
		userMap.put(user.getUsername(), user);
		return true;
	}
	
	public boolean isUserExist(String userName) {
		if (userMap.containsKey(userName)) {
			return true;
		}
		return false;
	}
	
	public NormalUser login(String uname, String pwd) {
		if (!userMap.containsKey(uname)) return null;
		NormalUser u = userMap.get(uname);
		if (!u.comparePwd(pwd)) return null;
		return u;
	}
	
	public boolean isUserCanLogin(String uName, String pwd) {
		return login(uName, pwd) != null;
	}
	
	@Override
	public Collection<NormalUser> getAll() {
		return userMap.values();
	}
	
	@Override
	public void update(NormalUser u) {
		//Nothing need to do here
	}

	@Override
	public boolean remove(String id) {
		for (NormalUser u : userMap.values()){
			if (u.getId().equals(id)){
				userMap.remove(u.getUsername());
				return true;
			}
		}
		return false;
	}

	@Override
	public NormalUser getById(String id){
		for (NormalUser u : userMap.values()){
			if (u.getId().equals(id)){
				return u;
			}
		}
		return null;
	}
}
